package com.magicborrow.activity;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayout;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import com.android.volley.VolleyError;
import com.magicborrow.Constants;
import com.magicborrow.R;
import com.magicborrow.beans.TagBean;
import com.magicborrow.beans.TagListBean;
import com.magicborrow.utils.VolleyTool;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import java.util.ArrayList;

public class TagActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener, VolleyTool.HTTPListener {


    private GridLayout glTag;
    private int checked;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tag);

        glTag = (GridLayout) findViewById(R.id.gl_tag);
        glTag.removeAllViews();
        initData();
      /*  for (int i = 0; i < 13; i++) {
            createTag("运动健康" + i, ImageUtil.readResource(this, R.drawable.ydjs_normal), ImageUtil.readResource(this, R.drawable.ydjs_pressed));
        }*/


        findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<String> tags = new ArrayList<String>();
                ArrayList<Integer> tagsId = new ArrayList<Integer>();
                for (int i = 0; i < glTag.getChildCount(); i++) {
                    CheckBox cb = (CheckBox) glTag.getChildAt(i);
                    if (cb.isChecked()) {
                        tags.add("" + cb.getText().toString());
                        tagsId.add(Integer.valueOf((String) cb.getTag()));
                    }
                }
                //tagsId = tagsId.substring(0, tagsId.length() - 2);
                setResult(Activity.RESULT_OK, getIntent().putExtra("tags", tags));
                setResult(Activity.RESULT_OK, getIntent().putExtra("tagsId", tagsId));
                finish();

            }
        });

    }

    private void initData() {
        VolleyTool.get(Constants.URL_GET_TAG_LIST, null, this, 0, TagListBean.class);
    }

    private void createTag(String text, String norBitmapUrl, String preBitmapUrl, int id) {
        final CheckBox cb = new CheckBox(this);
        cb.setTag("" + id);
        final StateListDrawable drawable = new StateListDrawable();
        cb.setCompoundDrawablePadding(getResources().getDimensionPixelOffset(R.dimen._5dp));


        ImageLoader.getInstance().loadImage(norBitmapUrl, new SimpleImageLoadingListener() {

            @Override
            public void onLoadingComplete(String imageUri, View view,
                                          Bitmap loadedImage) {
                super.onLoadingComplete(imageUri, view, loadedImage);
                drawable.addState(new int[]{-android.R.attr.state_checked, -android.R.attr.state_pressed}, new BitmapDrawable(getResources(), loadedImage));
                cb.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
            }

        });
        ImageLoader.getInstance().loadImage(preBitmapUrl, new SimpleImageLoadingListener() {

            @Override
            public void onLoadingComplete(String imageUri, View view,
                                          Bitmap loadedImage) {
                super.onLoadingComplete(imageUri, view, loadedImage);
                drawable.addState(new int[]{android.R.attr.state_checked, -android.R.attr.state_pressed}, new BitmapDrawable(getResources(), loadedImage));
                drawable.addState(new int[]{-android.R.attr.state_checked, android.R.attr.state_pressed}, new BitmapDrawable(getResources(), loadedImage));
                cb.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);

            }

        });
        GridLayout.LayoutParams params = new GridLayout.LayoutParams();
        params.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1f);
        params.setMargins(0, getResources().getDimensionPixelOffset(R.dimen._30dp), 0, 0);

        cb.setLayoutParams(params);
        cb.setButtonDrawable(new BitmapDrawable());
        cb.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.text_size_small_s));
        cb.setTextColor(getResources().getColor(R.color.text_color_nor));
        cb.setText("" + text);

        cb.setGravity(Gravity.CENTER);
        glTag.addView(cb);


    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            checked++;
            if (checked >= 3)
                for (int i = 0; i < glTag.getChildCount(); i++) {
                    CheckBox cb = (CheckBox) glTag.getChildAt(i);
                    cb.setEnabled(cb.isChecked());
                }

        } else {
            checked--;
            for (int i = 0; i < glTag.getChildCount(); i++) {
                CheckBox cb = (CheckBox) glTag.getChildAt(i);
                cb.setEnabled(true);
            }
        }


    }

    @Override
    public <T> void onResponse(T t, int requestCode) {
        TagListBean b = (TagListBean) t;
        if (((TagListBean) t).getCode() >= 0) {
            for (TagBean tg : b.getData()) {
                createTag(tg.getName(), Constants.ADDRESS + tg.getGrayIcon(), Constants.ADDRESS + tg.getIcon(), tg.getId());

            }
            for (int i = 0; i < glTag.getChildCount(); i++) {
                ((CheckBox) glTag.getChildAt(i)).setOnCheckedChangeListener(this);
            }

        } else {
            showShortMsg(b.getMessage());
        }

    }

    @Override
    public void onErrorResponse(VolleyError error, int requestCode) {

    }
}
